import pymongo
import docx,jieba
from pymongo import MongoClient as MC

class Mongo(object):
    def __init__(self):
        client = MC('localhost',27017)
        db = client.wordsdb
        self.words = db.words

    def add_date(self):
        file = docx.Document('word.docx')
        print("段落数："+str(len(file.paragraphs)))
        m=1
        for i in range(len(file.paragraphs)-1):
            if str(file.paragraphs[i].text).strip().isdigit():
                continue
            else:
                dic1={}
                str1=file.paragraphs[i].text.strip()
                lis1=str1.split(' ')
                str1=lis1[len(lis1)-1]
                str2 =file.paragraphs[i+1].text.strip()
                lis2=str2.split(' ')
                str2 =lis2[len(lis2)-1]
                if m%2!=0:
                    post={"key":str1,"value":str2}
                    self.words.insert(post)
                else:
                    pass
                m+=1

    def get_data(self,question):
        self.words.create_index([('key',1),('value',1)])
        results = self.words.find()
        res=[]
        for item in results:
            cut = jieba.cut(item['key'])
            cut = ','.join(cut)
            if question in cut:
                res.append([item['key'],item['value']])
        if len(res)==0:
            print('暂无相关信息或者你可以更改关键字')
            exit()
        else:
            return res

    def get_data2(self,question):
        cut = jieba.cut(question)
        cut = ','.join(cut)
        results = self.words.find()
        res =cut.split(',')
        resr=[]
        print(res)
        for item in results:
            for m in res:
                if m in item['key']:
                    resr.append([item['key'],item['value']])
                    break
        if len(resr)==0:
            print('暂无相关信息或者你可以更改关键字')
            exit()
        else:
            return resr



def main():
    mongo = Mongo()
    # mongo.add_date()


    question = input('输入你查询的关键字：').strip()
    # res = mongo.get_data2(question)
    res=mongo.get_data(question)
    num=0
    for i in res:
        num+=1
        print(num,':',i[0])
    number=int(input('选择你的问题编号').strip())
    number=number-1
    print(res[number][1])


if __name__ == '__main__':
    main()







